# API测试脚本
# 用于测试所有微服务的API端点

param(
    [string]$BaseUrl = "http://localhost:8080",
    [switch]$Verbose
)

$ErrorActionPreference = "Stop"

Write-Host "🧪 SmartCodeService API测试" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan
Write-Host ""

# 测试结果
$testResults = @{
    Total = 0
    Passed = 0
    Failed = 0
    Errors = @()
}

function Test-API {
    param(
        [string]$Name,
        [string]$Method,
        [string]$Url,
        [object]$Body = $null,
        [int]$ExpectedStatus = 200
    )
    
    $testResults.Total++
    
    try {
        Write-Host "测试: $Name" -NoNewline
        
        $params = @{
            Uri = $Url
            Method = $Method
            ContentType = "application/json"
            TimeoutSec = 10
        }
        
        if ($Body) {
            $params.Body = ($Body | ConvertTo-Json -Depth 10)
        }
        
        $response = Invoke-RestMethod @params -ErrorAction Stop
        
        if ($response.code -eq $ExpectedStatus -or $response.status -eq "UP") {
            Write-Host " ✅ 通过" -ForegroundColor Green
            $testResults.Passed++
            if ($Verbose) {
                Write-Host "   响应: $($response | ConvertTo-Json -Compress)" -ForegroundColor Gray
            }
            return $true
        } else {
            Write-Host " ❌ 失败 (状态码: $($response.code))" -ForegroundColor Red
            $testResults.Failed++
            $testResults.Errors += "$Name: 状态码不匹配"
            return $false
        }
    } catch {
        Write-Host " ❌ 错误: $($_.Exception.Message)" -ForegroundColor Red
        $testResults.Failed++
        $testResults.Errors += "$Name: $($_.Exception.Message)"
        return $false
    }
}

# 1. 健康检查测试
Write-Host "📊 健康检查测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

Test-API -Name "Gateway健康检查" -Method "GET" -Url "$BaseUrl/actuator/health"
Test-API -Name "代码补全服务健康检查" -Method "GET" -Url "http://localhost:8081/actuator/health"
Test-API -Name "代码生成服务健康检查" -Method "GET" -Url "http://localhost:8082/actuator/health"
Test-API -Name "代码分析服务健康检查" -Method "GET" -Url "http://localhost:8083/actuator/health"
Test-API -Name "LLM服务健康检查" -Method "GET" -Url "http://localhost:8084/actuator/health"
Test-API -Name "数据服务健康检查" -Method "GET" -Url "http://localhost:8085/actuator/health"
Test-API -Name "构建服务健康检查" -Method "GET" -Url "http://localhost:8086/actuator/health"
Test-API -Name "Agent服务健康检查" -Method "GET" -Url "http://localhost:8087/actuator/health"

Write-Host ""

# 2. 代码补全API测试
Write-Host "💡 代码补全API测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

$completionRequest = @{
    context = @{
        filePath = "test.cpp"
        code = "int main() {"
        cursorLine = 1
        cursorColumn = 15
        projectRoot = "C:/test"
    }
    maxResults = 10
}

Test-API -Name "代码补全" -Method "POST" -Url "$BaseUrl/api/completion/suggest" -Body $completionRequest

Write-Host ""

# 3. 代码导航API测试
Write-Host "🧭 代码导航API测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

$navigationRequest = @{
    symbol = "main"
    filePath = "test.cpp"
    projectRoot = "C:/test"
    code = "int main() { return 0; }"
    line = 1
    column = 5
}

Test-API -Name "跳转到定义" -Method "POST" -Url "$BaseUrl/api/completion/navigation/definition" -Body $navigationRequest
Test-API -Name "查找引用" -Method "POST" -Url "$BaseUrl/api/completion/navigation/references" -Body $navigationRequest

Write-Host ""

# 4. 诊断API测试
Write-Host "🔍 诊断API测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

$diagnosticRequest = @{
    filePath = "test.cpp"
    code = "int main() { return 0; }"
    projectRoot = "C:/test"
}

Test-API -Name "语法检查" -Method "POST" -Url "$BaseUrl/api/completion/diagnostic/syntax" -Body $diagnosticRequest

Write-Host ""

# 5. 代码生成API测试
Write-Host "⚙️ 代码生成API测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

$generationRequest = @{
    prompt = "生成一个Hello World函数"
    context = @{
        filePath = "test.cpp"
        projectRoot = "C:/test"
    }
}

Test-API -Name "代码生成" -Method "POST" -Url "$BaseUrl/api/generation/generate" -Body $generationRequest

Write-Host ""

# 6. Agent API测试
Write-Host "🤖 Agent API测试" -ForegroundColor Yellow
Write-Host "--------------------------------" -ForegroundColor Yellow

$agentRequest = @{
    message = "帮我生成一个Hello World函数"
    conversationId = "test-conv-001"
}

Test-API -Name "Agent对话" -Method "POST" -Url "$BaseUrl/api/agent/chat" -Body $agentRequest

Write-Host ""

# 测试总结
Write-Host "📊 测试总结" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan
Write-Host "总测试数: $($testResults.Total)" -ForegroundColor White
Write-Host "通过: $($testResults.Passed)" -ForegroundColor Green
Write-Host "失败: $($testResults.Failed)" -ForegroundColor Red

if ($testResults.Errors.Count -gt 0) {
    Write-Host ""
    Write-Host "错误详情:" -ForegroundColor Red
    foreach ($error in $testResults.Errors) {
        Write-Host "  - $error" -ForegroundColor Red
    }
}

$successRate = [math]::Round(($testResults.Passed / $testResults.Total) * 100, 2)
Write-Host ""
Write-Host "成功率: $successRate%" -ForegroundColor $(if ($successRate -ge 80) { "Green" } else { "Yellow" })

exit $(if ($testResults.Failed -eq 0) { 0 } else { 1 })

